// 个体行为记录表（户外活动路线）逻辑处理文件

/**
 * 计算户外活动评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估结果
 */
export function calculateOutdoorActivityAssessment(formData) {
  // 解析活动数据
  const activities = parseActivities(formData);
  
  // 统计活动信息
  const statistics = calculateStatistics(activities);
  
  // 生成评估摘要
  const summary = generateSummary(statistics);
  
  return {
    activities: activities,
    statistics: statistics,
    summary: summary,
    totalActivities: activities.length
  };
}

/**
 * 解析活动数据
 * @param {Object} formData - 表单数据
 * @returns {Array} 活动数组
 */
function parseActivities(formData) {
  const activities = [];
  const maxActivities = 6;
  
  for (let i = 1; i <= maxActivities; i++) {
    const activityCode = formData[`activityCode_${i}`];
    // 如果活动编号存在，则认为是有效活动
    if (activityCode && activityCode.trim() !== '') {
      const activity = {
        index: i,
        activityCode: formData[`activityCode_${i}`] || '',
        category: formData[`activityCategory_${i}`] || null,
        startTime: formData[`startTime_${i}`] || '',
        duration: formData[`duration_${i}`] || null,
        venue: formData[`venue_${i}`] || '',
        itemsUsed: formData[`itemsUsed_${i}`] || '',
        isWeekend: formData[`isWeekend_${i}`] || false,
        route: formData[`route_${i}`] || ''
      };
      
      // 转换时长为数字
      if (activity.duration && activity.duration !== '') {
        activity.duration = parseFloat(activity.duration) || 0;
      }
      
      // 转换类别为数字
      if (activity.category && activity.category !== '') {
        activity.category = parseInt(activity.category) || null;
      }
      
      activities.push(activity);
    }
  }
  
  return activities;
}

/**
 * 计算统计信息
 * @param {Array} activities - 活动数组
 * @returns {Object} 统计信息
 */
function calculateStatistics(activities) {
  if (activities.length === 0) {
    return {
      totalActivities: 0,
      totalDuration: 0,
      averageDuration: 0,
      categoryDistribution: {},
      venueDistribution: {},
      weekendActivities: 0,
      weekdayActivities: 0,
      mostCommonCategory: null,
      mostCommonVenue: null
    };
  }
  
  // 计算总时长和平均时长
  let totalDuration = 0;
  let validDurationCount = 0;
  
  // 活动分类统计
  const categoryDistribution = {};
  
  // 活动场所统计
  const venueDistribution = {};
  
  // 周末/工作日统计
  let weekendActivities = 0;
  let weekdayActivities = 0;
  
  activities.forEach(activity => {
    // 统计时长
    if (activity.duration && activity.duration > 0) {
      totalDuration += activity.duration;
      validDurationCount++;
    }
    
    // 统计活动分类
    if (activity.category) {
      categoryDistribution[activity.category] = (categoryDistribution[activity.category] || 0) + 1;
    }
    
    // 统计活动场所
    if (activity.venue && activity.venue.trim() !== '') {
      venueDistribution[activity.venue] = (venueDistribution[activity.venue] || 0) + 1;
    }
    
    // 统计周末/工作日
    if (activity.isWeekend === true || activity.isWeekend === 'true' || activity.isWeekend === 1) {
      weekendActivities++;
    } else {
      weekdayActivities++;
    }
  });
  
  const averageDuration = validDurationCount > 0 ? (totalDuration / validDurationCount).toFixed(1) : 0;
  
  // 找出最常见的活动分类
  let mostCommonCategory = null;
  let maxCategoryCount = 0;
  Object.keys(categoryDistribution).forEach(category => {
    if (categoryDistribution[category] > maxCategoryCount) {
      maxCategoryCount = categoryDistribution[category];
      mostCommonCategory = parseInt(category);
    }
  });
  
  // 找出最常见的活动场所
  let mostCommonVenue = null;
  let maxVenueCount = 0;
  Object.keys(venueDistribution).forEach(venue => {
    if (venueDistribution[venue] > maxVenueCount) {
      maxVenueCount = venueDistribution[venue];
      mostCommonVenue = venue;
    }
  });
  
  return {
    totalActivities: activities.length,
    totalDuration: totalDuration.toFixed(1),
    averageDuration: parseFloat(averageDuration),
    categoryDistribution: categoryDistribution,
    venueDistribution: venueDistribution,
    weekendActivities: weekendActivities,
    weekdayActivities: weekdayActivities,
    mostCommonCategory: mostCommonCategory,
    mostCommonVenue: mostCommonVenue
  };
}

/**
 * 生成评估摘要
 * @param {Object} statistics - 统计信息
 * @returns {Object} 评估摘要
 */
function generateSummary(statistics) {
  const categoryLabels = {
    1: '买菜购物',
    2: '运动锻炼',
    3: '棋牌麻将',
    4: '接送孙辈',
    5: '唱歌跳舞',
    6: '休闲步行',
    7: '跑腿',
    8: '集体活动'
  };
  
  const summary = {
    totalActivities: statistics.totalActivities,
    totalDuration: statistics.totalDuration,
    averageDuration: statistics.averageDuration,
    activityFrequency: statistics.totalActivities > 0 ? '活跃' : '不活跃',
    mainActivityType: statistics.mostCommonCategory ? categoryLabels[statistics.mostCommonCategory] : '无',
    mainVenue: statistics.mostCommonVenue || '无',
    weekendRatio: statistics.totalActivities > 0 
      ? ((statistics.weekendActivities / statistics.totalActivities) * 100).toFixed(1) 
      : 0
  };
  
  return summary;
}

/**
 * 验证户外活动表单数据
 * @param {Object} formData - 表单数据
 * @returns {Object} 验证结果
 */
export function validateOutdoorActivityForm(formData) {
  const errors = [];
  const warnings = [];
  
  // 个人信息字段已改为选填，不再进行必填验证
  // residenceAddress 和 recordDate 根据配置可能仍然是必填的，但这里先移除验证
  // 如果这些字段在配置中标记为必填，会在组件层面进行验证
  
  // 验证活动记录
  const activities = parseActivities(formData);
  if (activities.length === 0) {
    errors.push('请至少添加一条活动记录');
  }
  
  // 验证每条活动的必填项
  activities.forEach(activity => {
    if (!activity.activityCode || activity.activityCode.trim() === '') {
      errors.push(`第${activity.index}条活动的户外行为编号不能为空`);
    }
    
    if (!activity.startTime || activity.startTime === '') {
      warnings.push(`第${activity.index}条活动建议填写开始时间`);
    }
    
    if (!activity.duration || activity.duration === 0) {
      warnings.push(`第${activity.index}条活动建议填写步行时长`);
    }
    
    if (!activity.category) {
      warnings.push(`第${activity.index}条活动建议选择活动分类`);
    }
  });
  
  return {
    isValid: errors.length === 0,
    errors,
    warnings,
    hasWarnings: warnings.length > 0
  };
}

/**
 * 生成户外活动评估报告
 * @param {Object} assessmentResult - 评估结果
 * @param {Object} formData - 表单数据
 * @returns {Object} 评估报告
 */
export function generateOutdoorActivityReport(assessmentResult, formData) {
  const categoryLabels = {
    1: '买菜购物',
    2: '运动锻炼',
    3: '棋牌麻将',
    4: '接送孙辈',
    5: '唱歌跳舞',
    6: '休闲步行（如散步、逛公园、遛狗等）',
    7: '跑腿（如倒垃圾、取快递、取老人餐等）',
    8: '集体活动（如志愿活动、社区活动等）'
  };
  
  const basicInfo = {
    patientName: formData.patientName || '',
    patientId: formData.patientId || '',
    recordDate: formData.recordDate || '',
    residenceAddress: formData.residenceAddress || '',
    age: formData.age || '',
    gender: formData.gender || '',
    phone: formData.phone || '',
    remarks: formData.remarks || ''
  };
  
  const activities = assessmentResult.activities.map(activity => ({
    index: activity.index,
    activityCode: activity.activityCode,
    category: activity.category ? categoryLabels[activity.category] : '未分类',
    startTime: activity.startTime || '未填写',
    duration: activity.duration ? `${activity.duration}分钟` : '未填写',
    venue: activity.venue || '未填写',
    itemsUsed: activity.itemsUsed || '无',
    isWeekend: activity.isWeekend ? '是' : '否',
    route: activity.route || '未填写'
  }));
  
  const summary = {
    totalActivities: assessmentResult.totalActivities,
    totalDuration: `${assessmentResult.statistics.totalDuration}分钟`,
    averageDuration: `${assessmentResult.statistics.averageDuration}分钟`,
    mainActivityType: assessmentResult.summary.mainActivityType,
    mainVenue: assessmentResult.summary.mainVenue,
    weekendRatio: `${assessmentResult.summary.weekendRatio}%`
  };
  
  return {
    basicInfo: basicInfo,
    activities: activities,
    statistics: assessmentResult.statistics,
    summary: summary
  };
}

export default {
  calculateOutdoorActivityAssessment,
  generateOutdoorActivityReport,
  validateOutdoorActivityForm
};

